#!/usr/bin/python3
import subprocess
import yaml
import sys
import os
import re
import shutil

basePath = os.path.abspath(sys.argv[1])
targetPath = os.path.abspath(sys.argv[2])
parentPath = os.path.dirname(os.path.curdir)
with open(os.path.join(parentPath, "relation.yml"), "r") as f:
    data = yaml.load(f)

print(os.path.curdir)

files = os.listdir(targetPath)
for key in data.keys():
    keyPath = os.path.join(basePath, key)
    if not os.path.exists(keyPath):
        os.makedirs(keyPath)
    project_key_name = key
    if "extends" != data[key]["key"]:
        project_key_name = data[key]["key"]
    print(project_key_name)
    for file in files:
        if re.search("{}".format(project_key_name), file):
            print("--------------")
            print(file)
            print("--------------")

            shutil.copy(os.path.join(targetPath, file), keyPath)
            if data[key]["install"] == "jar":
                shutil.copy(
                    os.path.join(os.path.abspath(parentPath), "restart.sh"),
                    keyPath,
                )
    config_files_pro = os.path.join(os.path.join(targetPath, "config"), key)
    if os.path.exists(config_files_pro):
        config_files = os.listdir(config_files_pro)
        for cf in config_files:
            shutil.copy(
                os.path.join(config_files_pro, cf),
                keyPath,
            )
            if cf.endswith(".yml"):
                with open(os.path.join(config_files_pro, cf), "r") as ccf:
                    bootstrap_data = yaml.load(ccf)
                    print(bootstrap_data["spring"])
                    bootstrap_data["spring"]["cloud"]["nacos"]["discovery"][
                        "server-addr"
                    ] = "127.0.0.1:8848"
                    bootstrap_data["spring"]["cloud"]["nacos"]["config"][
                        "server-addr"
                    ] = "127.0.0.1:8848"
                    print(bootstrap_data)
                    shutil.copy(
                        os.path.join(config_files_pro, cf),
                        keyPath,
                    )
                    with open(os.path.join(keyPath, cf), "w") as ccf:
                        yaml.dump(bootstrap_data, ccf)
